package cn.ijero.waterfallflow;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cn.ijero.waterfallflow.data.FlowData;

public class MainViewModel extends AndroidViewModel {
    private List<String> pathList = new ArrayList<>();

    private MutableLiveData<List<FlowData.Data>> _liveData = new MutableLiveData<>();
    public LiveData<List<FlowData.Data>> liveData = _liveData;

    public MainViewModel(@NonNull Application application) {
        super(application);
        pathList.add("img_01.json");
        pathList.add("img_02.json");
        pathList.add("img_03.json");
    }

    public void loadData(int page) {
        try {
            if (page >= 3) {
                _liveData.setValue(new ArrayList<>());
                return;
            }
            InputStream inputStream = getApplication().getAssets().open(pathList.get(page));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder text = new StringBuilder();
            String readLine;
            while ((readLine = bufferedReader.readLine()) != null) {
                text.append(readLine);
            }

            Gson gson = new Gson();
            FlowData data = gson.fromJson(text.toString(), FlowData.class);
            List<FlowData.Data> newList = data.getData();
            for (FlowData.Data list : newList) {
                list.setHeight(new Random().nextInt(400) + 300);
            }
            _liveData.setValue(newList.subList(0, newList.size() - 1));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
